package com.triumphxx.readingreminderbackend.service;

import com.triumphxx.readingreminderbackend.entity.ReviewSchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.TimeZone;

/**
 * @author:triumphxx
 * @Date: 2025/11/20
 * @Time: 17:04
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: 复习服务
 **/

@Service
@Slf4j
public class ReminderService {

    @Autowired
    private NoteService noteService;
    @Autowired
    private SendMailService sendMailService;

    public ReminderService() {
        log.info("=== ReminderService 被实例化 ===");
    }

    // 每天八点二十点执行
    @Scheduled(cron = "0 20 8 * * ?", zone = "Asia/Shanghai")
//    @Scheduled(cron = "0 */5 * * * ?")
    public void checkAndSendReminders() {
        log.info("服务器当前时间: {}", LocalDateTime.now());
        log.info("北京时间: {}", ZonedDateTime.now(ZoneId.of("Asia/Shanghai")));
        log.info("时区: {}", TimeZone.getDefault().getID());
        log.info("开始检查复习提醒..." + LocalDateTime.now());
        List<ReviewSchedule> reviewsToSend = noteService.getAllTodayReviews();

        for (ReviewSchedule review : reviewsToSend) {
            sendReminder(review);
        }

        log.info("今天有 " + reviewsToSend.size() + " 条笔记需要复习");

        // 如果有复习任务，发送汇总邮件
        if (!reviewsToSend.isEmpty()) {
            sendMailService.sendSummaryEmail(reviewsToSend);
        }
    }

    private void sendReminder(ReviewSchedule review) {
        // 发送控制台提醒
        log.info("提醒: 需要复习笔记 \"" + review.getNote().getTitle() + "\"");
        log.info("阶段: 第" + review.getStage() + "次复习");
        log.info("链接: " + review.getNote().getYuqueUrl());

        // 发送邮件提醒
        sendMailService.sendEmailReminder(review);

        // 更新最后提醒时间
        review.getNote().setLastReminded(LocalDateTime.now());
        noteService.save(review.getNote());
    }

}